
package Nisha.designPatterns;
public class Singleton {

	private static Singleton instance;
	private Singleton()
	{		
	}
	
	@SuppressWarnings("static-access")
	public static Singleton getInstance() throws InterruptedException
	{

		if(instance==null)
		{
			if(Thread.currentThread().getName().equals("thread1"))
				//Thread.currentThread().wait();
				Thread.currentThread().sleep(10000);
		    instance = new Singleton();
			System.out.println("instance created from thread "+Thread.currentThread().getName());	
		}
	return instance;
	}
	
	
	public static void main(String[] args) {
		
		SingletonThread thread1 = new SingletonThread("thread1");
		thread1.run();

		SingletonThread thread2 = new SingletonThread("thread2");
		thread2.run();
		SingletonThread thread3 = new SingletonThread("thread3");
		thread3.run();
		SingletonThread thread4 = new SingletonThread("thread4");
		thread4.run();
	}

}

class SingletonThread implements Runnable
{
   public SingletonThread(String name)
   {
	   Thread.currentThread().setName(name);	   
   }
	@Override
	public void run() {
		
	  try {
		Singleton s1 = Singleton.getInstance();
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	  //System.out.println("instance created from thread "+Thread.currentThread().getName());
	}
	
}
